package com.mediacloud.app.newsmodule.activity.military_encyclopedia

import android.app.Activity
import android.util.TypedValue
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.view.WebBrowser
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.WebViewPageActivity
import com.mediacloud.app.newsmodule.fragment.imagetext.HtmlFormat
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.utils.ActivityScanner
import kotlinx.android.synthetic.main.activity_detail_military_ency_detail.*
import org.jsoup.Jsoup
import org.jsoup.select.Elements

class MilitaryEncyclopediaDirectoryRelationAdapter : BaseQuickAdapter<EntryDirectoryRelationList,BaseViewHolder>(R.layout.item_bk_directory_relation) {
    var webDirectoryContent:WebBrowser?=null
    var entryRefList: List<EntryRefList>?=null//参考资料
    var linkRelationList: List<LinkRelationList>?=null//相关引用词条
    var zoom: Int = 0
    override fun convert(helper: BaseViewHolder, item:EntryDirectoryRelationList) {
         val tvDirectoryName = helper.getView<TextView>(R.id.tvDirectoryName)
         webDirectoryContent = helper.getView(R.id.webDirectoryContent)
         tvDirectoryName.text = item.directoryName
        if (zoom != 0){
            val webSettings = webDirectoryContent?.settings
            webSettings?.textZoom = zoom
            tvDirectoryName?.let{
                val textSize: Float = it.context.resources.getDimension(R.dimen.sp_18) * (zoom / 100f)
                tvDirectoryName?.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
            }
        }
         parseHtml(item.directoryContent)
    }

    fun resizeText(zoom: Int){
        this.zoom = zoom
        notifyDataSetChanged()
    }

    @JavascriptInterface
    fun openDialog(id:String) {
        entryRefList?.let{
            it.forEach {item->
                if (item.refId == id.toLongOrNull()){
                    MarkingDialog.Builder().builder(webDirectoryContent?.context)
                        .setTitle("[${item.refId}]${item.articleTitle}. ${item.websiteName}")
                        .setMsg("[发表日期${item.publishDate}]")
                        .setClick {view->
                            if(view.context is Activity){
                                WebViewPageActivity.start(
                                    item.websiteName,
                                    item.websiteUrl,
                                    view.context as Activity)
                            }else{
                                val activity: Activity? = ActivityScanner.findActivity(view)
                                activity?.let {
                                    WebViewPageActivity.start(
                                        item.websiteName,
                                        item.websiteUrl,
                                        activity)
                                }

                            }
                        }
                        .create().show()
                }
            }
        }
        linkRelationList?.let{
            it.forEach {item->
                if (item.articleId == id.toLongOrNull()){
                    MarkingDialog.Builder().builder(webDirectoryContent?.context)
                        .setTitle(item.title)
                        .setMsg(item.shortTitle)
                        .setClick {view->
                            var articleItem = ArticleItem()
                            articleItem.id = item.articleId
                            articleItem.isCloseActivity = false
                            articleItem.type = 37
                            NewsItemClickUtils.OpenItemNewsHandle(view.context, articleItem.type, articleItem, null)

                        }
                        .create().show()
                }
            }
        }
    }

    fun parseHtml(html: String) {
        webDirectoryContent?.settings?.javaScriptEnabled = true
        webDirectoryContent?.addJavascriptInterface(this, "ClickTip")
        webDirectoryContent?.setWebViewClient(object :WebBrowser.WebClient(webDirectoryContent?.context,webDirectoryContent){
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                return true
            }
        })
        val doc = Jsoup.parse(html)
        val bodyNode: Elements? = doc.getElementsByTag("head")
        if (bodyNode != null && bodyNode.size > 0) {
            bodyNode[0].append("\n<script src=\"file:///android_asset/web/webnews.txt\"/>")
        }
        val aTags = doc.getElementsByTag("a")
        for (i in 0 until aTags.size) {
            val aElement = aTags[i]
            aElement.attr("href","https://baidu.com")
            aElement.attr("onclick", "wikiContentClick(this)")
        }
        var result = doc.toString()
        webDirectoryContent?.loadDataWithBaseURL(
            null,
            HtmlFormat.getNewContent(result),
            "text/html; charset=utf-8",
            "utf-8",
            null
        )

    }

}